package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

@Data
@ConfigurationProperties("jwt.config")
public class JwtUtil {
    private String key;
    private long ttl;

    /**
     * 生成jwt
     */
    public String createJWT(String id,String subject,String role){
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setIssuedAt(new Date())
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256,key)
                .claim("roles",role);
        //添加的时间大于0才能添加
        if (ttl > 0) {
            jwtBuilder.setExpiration( new Date( System.currentTimeMillis() + ttl));
        }
        String compact = jwtBuilder.compact();
        return compact;

    }
    /**
     * 解析jwt
     */
    public Claims parseJWT(String token){
            return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

}
